﻿using System;
using System.Windows.Forms;
using EncryptionLib.Signature;
using EncryptionLib.Users;
using System.IO;
using System.Diagnostics;

namespace WordDiSign
{
    public partial class frmVerify : Form
    {
        public string DocumentPath
        {
            get;
            set;
        }

        public IUserManager UserManager
        {
            get;
            set;
        }

        public frmVerify()
        {
            InitializeComponent();
        }

        
        private void btnSignatureFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.AddExtension = dlg.AutoUpgradeEnabled
                = dlg.CheckFileExists = dlg.CheckPathExists 
                = dlg.RestoreDirectory = true;
            dlg.Title = "Choose a place to save signature file";
            dlg.DefaultExt = "sig";
            dlg.Filter = "Signature file (*.sig)|*.sig|All files(*.*)|*.*||";
            dlg.FilterIndex = 0;

            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                txtSignatureFile.Text = dlg.FileName;
            }
        }

        private void llblHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show(this, "Finally, you clicked me...\r\nI'm sorry because it's hard for you to use this add-in,\r\n so find the way to use it by yourself!",
                "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnVerify_Click(object sender, EventArgs e)
        {
            string sSignFile = txtSignatureFile.Text;
            string sFile = txtDoc.Text;
            if(string.IsNullOrEmpty(sSignFile))
            {
                MessageBox.Show(this,
                    "Please specify a valid signature file.",
                    "Err...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSignatureFile.Focus();
                return;
            }

            try
            {
                for(int i = UserManager.GetCount() - 1; i >= 0; --i)
                {
                    UserData userData = UserManager.GetUser(i);
                    string sCpFile = System.IO.Path.GetTempFileName();
                    File.Copy(sFile, sCpFile, true);
                    bool bSuccess = Signer.Verify(userData, sCpFile/*sFile*/, sSignFile);
                    try
                    {
                        File.Delete(sCpFile);
                    }
                    catch (System.Exception /*ex*/)
                    {
                        Debug.WriteLine("Error when deleting temp file.");
                    }
                    if(bSuccess)
                    {
                        MessageBox.Show(this,
                            string.Format("Verification was completed successfully.\r\n\r\nSigner: {0}", userData.Email),
                            "Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Close();
                        return;
                    }
                }
                MessageBox.Show(this,
                            "Cannot verify this document!\r\n\r\nIt was signed by an unknown user,\r\nor the signature file is invalid,\r\n or the document has been modified.",
                            "Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(this,
                    string.Format("An unexpected error hass occurred when verifying.\r\n\r\nError: {0}", ex.Message),
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSignatureFile.Focus();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void frmVerify_Load(object sender, EventArgs e)
        {
            txtDoc.Text = DocumentPath;
            txtSignatureFile.Text = DocumentPath + ".sig";
        }
    }
}
